﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Crm2011.Framework.Core;



namespace Crm2011.Framework.Connect
{
    public class ConnectionList
    {
        public static readonly ConnectionList Current = new ConnectionList("CrmConnectionProfiles.xml");


        private List<ConnectionProfile> _list;
        private readonly string _fileName;
        private const int MaxItemCount = 16;



        private ConnectionList(string listName)
        {
            _fileName = PublicFunc.GetFullFilePath(@"%AppData%\Schmidt e-Services GmbH\" + listName, null, false);
            _list = File.Exists(_fileName) ? SerializationHelper.Deserialize<List<ConnectionProfile>>(File.ReadAllText(_fileName)) : new List<ConnectionProfile>();
        }



        public IEnumerable<ConnectionProfile> Items
        {
            get { return _list; }
            internal set
            {
                _list = value.ToList();
                saveToDisc();
            }
        }



        /// <summary>
        /// Adds the specified connection profile.
        /// </summary>
        /// <param name="connectionProfile">The connection profile.</param>
        /// <returns>true when a new profilel was added. false in case of an existing profile.</returns>
        public bool Add(ConnectionProfile connectionProfile)
        {
            var existingItem = _list.FirstOrDefault(i => i.ConnectionId == connectionProfile.ConnectionId);
            if (existingItem != null)
                _list.Remove(existingItem); // remove to be inserted on top

            if (_list.Count == MaxItemCount)
                _list.Remove(_list[MaxItemCount - 1]);

            _list.Insert(0, connectionProfile);
            saveToDisc();
            return (existingItem == null);
        }



        public bool Delete(Guid profileId)
        {
            var existingItem = _list.FirstOrDefault(i => i.ConnectionId == profileId);
            if (existingItem != null)
            {
                _list.Remove(existingItem);
                saveToDisc();
            }
            return (existingItem == null);
        }



        private void saveToDisc()
        {
            string directoryName = Path.GetDirectoryName(_fileName);
            if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);
            File.WriteAllText(_fileName, SerializationHelper.Serialize(_list));
        }
    }
}